package com.winit.openapi.interceptor.validator.impl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.interceptor.validator.OAuth2APIRequestValidator;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.oauth.manager.UserAuthorizationManager;
import com.winit.openapi.oauth.vo.APIClientVo;
import com.winit.openapi.oauth.vo.UserAuthorizationVo;
import com.winit.openapi.util.RequestUtil;
import com.winit.openapi.util.ValidateUtil;

@Service("oAuth2UserRequestHandler")
public class OAuth2UserRequestHandler extends OAuth2APIRequestValidator<HttpServletRequest> {

    private static final Logger      logger = LoggerFactory.getLogger(OAuth2UserRequestHandler.class);

    @Resource
    private UserAuthorizationManager userAuthorizationManager;

    @Override
    public void checkAccessToken(HttpServletRequest request) throws ApiException {
        RequestMsg requestMsg = RequestUtil.getRequestMsg(request);
        if (StringUtils.isBlank(requestMsg.getClient_id()) || StringUtils.isBlank(requestMsg.getApp_key())) {
            return;
        }
        // 当有应用和用户信息时候，需要校验授权信息
        UserAuthorizationVo authVo = userAuthorizationManager.queryByClientKeyAndUserName(requestMsg.getClient_id(),
            requestMsg.getApp_key());

        // 未授权
        if (authVo == null || StringUtils.isBlank(authVo.getAccessToken())) {
            CommandContext ctx = CommandContext.getContext();
            // oauth2应用信息
            APIClientVo clientVo = ctx.get(ApiConstant.API_CLIENT);
            throw new ApiException(ErrorCode.API_AUTH_UNAUTH_ERROR, clientVo.getClientAuthUrl());
        }
        // 授权过期
        if (authVo.getExpireTime().getTime() < System.currentTimeMillis()) {
            throw new ApiException(ErrorCode.API_AUTH_EXPIRED_ERROR);
        }
        // 授权被锁定，需要激活
        if ("N".equals(authVo.getIsActive())) {
            throw new ApiException(ErrorCode.API_AUTH_LOCKED_ERROR);
        }
    }

    @Override
    public void doAuth(HttpServletRequest request) {
        long start = System.currentTimeMillis();
        checkAccessToken(request);
        long end = System.currentTimeMillis();
        long time = end - start;
        if (time >= 100) {
            logger.warn("查询用户授权信息超时告警：查询耗时：" + time + " ms");

        }

    }

    @Override
    public void doCheckData(HttpServletRequest request) {
        JSONObject json = super.checkBaseData(request);
        ValidateUtil.validNotNull(json, "client_id");
        ValidateUtil.validMaxLength(json, "client_id", 120);
        ValidateUtil.validNotNull(json, "client_sign");
        ValidateUtil.validMaxLength(json, "client_sign", 32);
        ValidateUtil.validNotNull(json, "platform");
        ValidateUtil.validMaxLength(json, "platform", 50);

    }

}
